<template>
  <div class="change-password">
    <Card>
      <Form ref="passwordForm" :model="form" :rules="rules" label-width="100px">
        <FormItem label="旧密码" prop="oldPassword">
          <Input type="password" v-model="form.oldPassword" placeholder="请输入旧密码" />
        </FormItem>

        <FormItem label="新密码" prop="newPassword">
          <Input type="password" v-model="form.newPassword" placeholder="请输入新密码" />
        </FormItem>

        <FormItem label="确认密码" prop="confirmPassword">
          <Input type="password" v-model="form.confirmPassword" placeholder="请确认新密码" />
        </FormItem>

        <FormItem>
          <Button type="primary" @click="handleSubmit" style="margin-left: 100px;">提交</Button>
          <Button @click="handleCancel" style="margin-left: 50px">取消</Button>
        </FormItem>
      </Form>
    </Card>
  </div>
</template>

<script>
import { ref } from 'vue';
import { updatePassword, logout } from '@/api/user'; // 导入修改密码API接口
import { Message } from 'view-ui-plus'; // 视图库的消息提示
import router from '@/router';

export default {
  setup() {
    const form = ref({
      oldPassword: '',
      newPassword: '',
      confirmPassword: '',
    });

    const rules = {
      oldPassword: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 2, message: '密码长度至少2位', trigger: 'blur' },
      ],
      confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error('密码不能为空'));
            } else if (value !== form.value.newPassword) {
              callback(new Error('两次输入的密码不一致'));
            } else {
              callback();
            }
          },
          trigger: 'blur',
        },
      ],
    };

    const handleSubmit = () => {
      const passwordForm = form.value;

      if (passwordForm.newPassword === '' || passwordForm.confirmPassword === '') {
        Message.error('密码不能为空');
        return;
      }

      if (passwordForm.newPassword !== passwordForm.confirmPassword) {
        Message.error('两次输入的密码不一致');
        return;
      }

      const token = document.cookie
        .split('; ')
        .find((row) => row.startsWith('token='))
        ?.split('=')[1];

      const query = {
        oldPassword: passwordForm.oldPassword,
        newPassword: passwordForm.newPassword,
      };

      updatePassword(query, token)
        .then((res) => {
          if (res.code === 0) {
            Message.success('密码修改成功');
            router.push('/login');
            handleCancel();
          } else {
            Message.error('密码修改失败：' + res.message);
          }
        })
        .catch((error) => {
          console.error('密码修改失败：', error);
          Message.error('密码修改失败，请重试');
        });
    };

    const handleCancel = () => {
      form.value.oldPassword = '';
      form.value.newPassword = '';
      form.value.confirmPassword = '';
    };

    return {
      form,
      rules,
      handleSubmit,
      handleCancel,
    };
  },
};
</script>

<style scoped>
.change-password {
  max-width: 400px;
  margin: 50px auto;
}

.ivu-form-item {
  margin-bottom: 20px;
}
</style>
